# coding: utf-8
import paramiko #实现了SSHv2协议的一个python库
import os
import time
 
# 定义一个类，表示一台远端linux主机
class Linux(object):
    # 通过IP, 用户名，密码，超时时间初始化一个远程Linux主机
    def __init__(self, ip, username, password, port=22, timeout=3000):
        self.ip = ip
        self.username = username
        self.password = password
        self.port = port
        self.timeout = timeout
 
    def __get_all_files_in_local_dir(self, local_dir):
        # 用于保存所有文件的列表
        all_files = list()
 
        # 获取当前指定目录下的所有目录及文件，包含属性值
        files = os.listdir(local_dir)
        for x in files:
            # local_dir目录中每一个文件或目录的完整路径
            filename = os.path.join(local_dir, x)
            # 如果是目录，则递归处理该目录
            if os.path.isdir(filename):
                all_files.extend(self.__get_all_files_in_local_dir(filename))
            else:
                datestr = time.strftime("%Y%m%d", time.localtime())
                datestr_x = 'hmfs_audit_' + datestr + '_02'
                if datestr_x in filename:
                    all_files.append(filename)
        return all_files
 
    def sftp_put_dir(self, local_dir, remote_dir):
        t = paramiko.Transport(sock=(self.ip, self.port))
        t.connect(username=self.username, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(t)
 
        # 获取本地指定目录及其子目录下的所有文件
        all_files = self.__get_all_files_in_local_dir(local_dir)
        # 按照日期创建目录
        datestr = time.strftime("%Y%m%d", time.localtime())
        datestr = datestr + '_py'
        try:
            sftp.stat(datestr)
            print('目录%s已存在' % datestr)
        except Exception as e1:
            sftp.mkdir(datestr)
            print('创建目录%s' % datestr)

        # 依次put每一个文件
        for x in all_files:
            filename = os.path.split(x)[-1]
            remote_filename = os.path.join(remote_dir, datestr, filename)
            print (x)
            print (remote_filename)
            print (u'Put文件%s传输到%s中...' % (filename,self.ip))
            sftp.put(x, remote_filename)

'''
从本地制定目录向附件服务器传输文件
'''
if __name__ == '__main__':
    
    remote_path = r'/'
    local_path = r'/backup/backup_data/data/'

    host = Linux('172.19.14.202','szjcy', '14972jYs', 9922) 
    host.sftp_put_dir(local_path, remote_path)